<template>
    <div id="emergencyNumberManage" class="center_div">
        <div class="searchForm searchFormDataManageBtn22px" style="margin-top: 1%;margin-left: 1%;">
            <el-form :inline="true"  class="demo-form-inline">
                <el-form-item label="号码">
                    <el-input v-model="number" ></el-input>

                </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="querySearch"class="dataManageBtn22BtnpPx">查询</el-button>
                    <el-button type="primary"  @click="add"class="dataManageBtn22BtnpPx">添加</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table-wrap" >
            <el-table
                    :data="tableData"
                    style="width:100%;text-align: center;"
                    border
                    header-align="center"
                    cell-class-name="dataManage18px"
                    :header-cell-style="headerCellClassName">
                <el-table-column align="center" v-for="title in tableTitle" :prop="title.prop" :label="title.label":show-overflow-tooltip="title.overflowTooltip">
                </el-table-column>
                <template v-if="buttons && buttons.length!==0">
                    <el-table-column
                            class="align-right"
                            width="250px"
                            header-align="center"
                            label="操作"
                            align="center" >
                        <template slot-scope="scope">
                            <el-button v-for="button in buttons"
                                       @click="operate(scope.row,button.href)" :type="button.type"
                                       class="el-button el-button--text dataManageBtn22px">{{button.label}}
                            </el-button>
                        </template>
                    </el-table-column>
                </template>
            </el-table>
            <el-pagination
                    class="dataManage18px"
                    layout="total,prev, pager, next"
                    background
                    @current-change="changePageNum"
                    :current-page="pageNum"
                    :page-size="pageSize"
                    :total="total">
            </el-pagination>
        </div>
        <div>
            <el-dialog :title="title"
                       :visible.sync="showBox"
                       width="50%"
                       @close="closeDialog"

                       append-to-body>
                <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
                    <el-row>
                        <!--  <el-col :span="12">
                              <el-form-item label="前缀"  prop="prefix">
                                  <el-input type="number" v-model.number="form.prefix" clearable></el-input>
                              </el-form-item>
                          </el-col>-->
                        <el-col :span="22">
                            <el-form-item label="号码" prop="number">
                                <!--  onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"-->
                                <el-input v-model="form.number" clearable type="number"
                                          onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!--      <el-col :span="12">
                                  <el-form-item label="区号"  prop="areaCode">
                                      &lt;!&ndash; onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"&ndash;&gt;
                                      <el-input  v-model.number="form.areaCode"  type="number" :min="0"
                                               >
                                      </el-input>
                                  </el-form-item>
                              </el-col>-->
                        <el-col :span="22">
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="form.name" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!--<el-row>
                        <el-col :span="12">
                            <el-form-item label="系统类型" :required="true">
                                <el-select v-model="form.system" placeholder="请选择">
                                    <el-option
                                            v-for="item in systemOptions"
                                            :key="item.System_ID"
                                            :label="item.System_alias"
                                            :value="item.System_ID">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                        </el-col>
                    </el-row>-->
                    <el-row>
                        <el-form-item label="描述" prop="remark">
                            <el-input v-model="form.remark" type="textarea"></el-input>
                        </el-form-item>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button  @click="closeBox"class="dataManageBtn22BtnpPx">取 消</el-button>
                    <el-button type="primary" @click="addEmergencyNumber" v-show="showAdd"class="dataManageBtn22BtnpPx">添 加</el-button>
                    <el-button type="primary" @click="updateEmergencyNumber" v-show="!showAdd"class="dataManageBtn22BtnpPx">修 改</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
  import EmergencyNumberManage from '@/api/dataManages/EmergencyNumberManage';

  export default {
    name: 'EmergencyNumberManage',
    props: {
      FleetId: Number,
      userId: Number,
    },
    data() {
      var validateNumber = (rule, value, callback) => {
        console.log(this.form.number);

        if (value === '') {
          callback(new Error('请输入号码'));
        } else if (value.length > 5) {
          callback(new Error('号码不能超过20位'));
          // this.form.number.substring(0, 20)
        }
      }
      return {
        number: '',
        tableTitle: [
          // {label: '前缀', prop: 'prefix'},
          {label: '号码', prop: 'number',overflowTooltip:true},
          {label: '名称', prop: 'name',overflowTooltip:true},
          // {label: '区号', prop: 'areaCode'},
          //{label: '系统类型', prop: 'System_alias'},
          {label: '描述', prop: 'remark',overflowTooltip:true},
        ],
        rules: {
          /*   prefix: [
               {required: true, message: '请输入前缀', trigger: 'blur'},
               {pattern: /^-?\d+\.?\d*$/, message: '前缀必须为数字', trigger: 'blur'},
             ],*/
          number: [
            {required: true,message: '请输入号码', trigger: 'blur'},
            // {pattern: /^-?\d+\.?\d*$/, message: '号码必须为数字', trigger: 'blur'},
            // {min: 1, max: 30, message: '长度不能超过30个数字', trigger: 'blur'},
            // {type:'number'}
          ],
          /*  areaCode: [
              {required: true, message: '请输入区号', trigger: 'blur'},
              {pattern: /^-?\d+\.?\d*$/, message: '区号必须为数字', trigger: 'blur'}
            ],*/
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'},
            {min: 1, max: 30, message: '长度不能超过30个字符', trigger: 'blur'},
          ],
          remark: [
            {min: 1, max: 128, message: '长度不能超过128个字符', trigger: 'blur'},
          ],
        },
        tableData: [],
        total: 0,
        pageNum: 1,
        pageSize: 8,
        buttons: [{label: '编辑', href: 'update'}, {label: '删除', href: 'delete'}],
        showBox: false,
        showAdd: true,
        title: '',
        form: {
          id: '',
          prefix: '',
          number: '',
          name: '',
          areaCode: '',
          system: '',
          remark: '',
        },
        systemOptions: [],
      };
    },
    created() {
      this.changeDmgPage();
    },
    mounted: function() {
      this.query();
      // this.getSystem();
    },
    computed:{
      remarkA(){
        return this.form.remark;
      },
      numberA(){
        return this.form.number;
      }
    },
    watch:{
      remarkA(val){
        if(val.length>100){
          this.$message.error("描述不能超过100位字符")
          this.form.remark.substring(0,100);
        }
      },
      numberA(val){
        if(val.length>10){
          this.$message.error("号码不能超过10位数字")
          this.form.number.substring(0,10);
        }
      }
    },
    methods: {
      querySearch(){
        this.query(1);
        this.pageNum = 1;
      },
      changeDmgPage(){
        let w = window.screen.width;
        let h = window.screen.height;
        if (w == 1920) {
          if (h == 1080) {
          } else {
            this.pageSize = 11
          }
        }
      },
      //表头样式
      headerCellClassName() {
        return 'font-size:18px;color:#515A6E;padding:10px 0px 10px 0px !important;background:#F5F5F6;border:1px solid #EBEBEB';
      },
      //表格样式
      cellStyleClassName() {
        return 'font-size:13px;text-align:center;color:#606266;padding:5px 0px 5px 0px !important;border:1px solid #EBEBEB';
      },
      getSystem: function() {
        EmergencyNumberManage.getSystem({}).then(res => {
          var data = res;
          if (res.success) {
            this.systemOptions = data.obj.list;
          } else {
            this.$message(res.msg);
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
        });
      },
      formClear: function() {
        this.form.id = '';
        this.form.prefix = '';
        this.form.number = '';
        this.form.name = '';
        this.form.areaCode = '';
        this.form.system = '';
        this.form.remark = '';
      },
      query: function(pageNum) {
        var data = {
          number: this.number || '',
          pageNum: pageNum || this.pageNum,
          fleetId: this.FleetId,
          pageSize: this.pageSize,
        };

        EmergencyNumberManage.getEmergencyNumber(data).then(res => {
          var data = res;
          if (res.success) {
            this.tableData = data.obj.list;
            this.total = data.obj.total;
            this.number = '';
          } else {
            this.$message('');
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
        });
      },
      add: function() {
        var that = this;
        that.formClear();
        that.showBox = true;
        that.showAdd = true;
        that.title = '添加紧急号码';
      },
      closeDialog() {

        this.$nextTick(function() {
          this.$refs['form'].resetFields();
        });
      },
      addEmergencyNumber: function() {
        var validate = false;
        this.$refs['form'].validate((valid) => {
          if (valid) {
            validate = true;
          } else {
            console.log('error submit!!');
            validate = false;
            return false;
          }
        });
        if (validate === false) {
          return;
        }
        var that = this;
        var data = {
          prefix: this.form.prefix,
          number: this.form.number,
          name: this.form.name,
          areaCode: this.form.areaCode,
          // system:this.form.system,
          remark: this.form.remark,
          fleetId: this.FleetId,
        };
        var auditData = {
          dcId: that.$store.getters.userAccount,
          type: 5,
          status: '成功',
          describe: that.$store.getters.userName + "添加紧急号码:" + data.name,
          time: new Date,
          fleetId: that.$store.getters.scsFleetId,
          detailType: 31,
          remark: '',
        };

        EmergencyNumberManage.addEmergencyNumber(data).then(res => {
          if (res.success) {
              this.GlobalFunc.GlaAddAudit(auditData);
              that.closeBox();
              that.$message.success('添加成功');
              that.query();
            } else {
                if (res.obj == 1) {
                  that.$message.error('号码不能重复!');
                } else {
                  auditData.status = "失败";
                  this.GlobalFunc.GlaAddAudit(auditData);
                  that.$message.error('添加失败');
              }
          }
        }).catch(err => {
          // 异常情况
          console.log(err);
          auditData.status = "异常";
          this.GlobalFunc.GlaAddAudit(auditData);
        });
      },
      updateEmergencyNumber: function() {
        var validate = false;
        this.$refs['form'].validate((valid) => {
          if (valid) {
            validate = true;
          } else {
            console.log('error submit!!');
            validate = false;
            return false;
          }
        });
        if (validate === false) {
          return;
        }
        var that = this;
        var data = {
          id: that.form.id,
          prefix: this.form.prefix,
          number: this.form.number,
          name: this.form.name,
          areaCode: this.form.areaCode,
          remark: this.form.remark,
          fleetId: this.FleetId
        };
        var auditData = {
          dcId: that.$store.getters.userAccount,
          type: 5,
          status: '成功',
          describe: that.$store.getters.userName + "修改紧急号码:" + data.name,
          time: new Date,
          fleetId: that.$store.getters.scsFleetId,
          detailType: 31,
          remark: '',
        };
            EmergencyNumberManage.updateEmergencyNumber(data).then(res => {
          if (res.success) {
            this.GlobalFunc.GlaAddAudit(auditData);
            this.closeBox();
            this.$message.success('编辑成功');
            this.query();

          } else {
                if (res.obj == 1) {
                  this.$message.error('号码不能重复!');
                } else {
                  auditData.status = "失败";
                  this.GlobalFunc.GlaAddAudit(auditData);
                  this.$message.error('编辑失败');
                }

            }

        }).catch(err => {
          // 异常情况
              auditData.status = "异常";
              this.GlobalFunc.GlaAddAudit(auditData);

              console.log(err);
        });
      },
      closeBox: function() {
        this.showBox = false;
      },
      operate: function(row, href) {
        if (href.indexOf('update') !== -1) {
          console.info('ssssdddd');
          this.showBox = true;
          this.showAdd = false;
          this.title = '编辑紧急号码';
          this.form.id = row.id;
          this.form.prefix = row.prefix;
          this.form.number = row.number;
          this.form.areaCode = row.areaCode;
          this.form.name = row.name;
          //  that.form.system=row.system;
          this.form.remark = row.remark;
        } else {
          console.log("删除");
          var auditData = {
            dcId: this.$store.getters.userAccount,
            type: 5,
            status: '成功',
            describe: this.$store.getters.userName + "删除紧急号码:" + row.number,
            time: new Date,
            fleetId: this.$store.getters.scsFleetId,
            detailType: 31,
            remark: '',
          };

          this.$confirm('是否确定删除', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            EmergencyNumberManage.deleteEmergencyNumber({id: row.id}).then(res => {
              if (res.success) {
                this.GlobalFunc.GlaAddAudit(auditData);

                this.$message.success('删除成功');
                //此时已经实现删除操作，所以total的值需要减1，Math.ceil是向上取整，保证始终大于等于1
                const totalPage = Math.ceil((this.total - 1) / this.pageSize);
                //记住删除最后一条数据时当前码是最后一页
                const tempPageNum = this.pageNum > totalPage ? totalPage : this.pageNum;
                //实现跳转
                this.pageNum = tempPageNum < 1 ? 1 : tempPageNum;
                this.query();
              }else {
                  auditData.status = "失败";
                this.GlobalFunc.GlaAddAudit(auditData);

              }
            }).catch(err => {
              auditData.status = "异常";
              this.GlobalFunc.GlaAddAudit(auditData);

              // 异常情况
              console.log(err);
            });
          }).catch(() => {
          });

        }
      },
      changePageNum: function(val) {
        this.pageNum = val;
        this.query();
      },
    },
  };
</script>

<style scoped>
    .el-dialog__body {
        /*height: 30vh;*/
        overflow: auto;
    }
    /deep/ .el-form-item__label{
        font-size: 22px!important;
    }
    /deep/ .el-input__inner{
        font-size: 22px!important;
    }
    /deep/ .el-dialog__title {
        font-size: 22px;
    }
    /deep/ .el-textarea__inner {
        font-size: 18px;
    }
    /deep/ .el-icon-close:before {
        font-size: 25px;
    }
    /*分页修改开始*/
    .el-pagination /deep/ .el-pagination__total {
        font-size: 20px;
        line-height: 60px;
    }.el-pagination /deep/ button /deep/ .el-icon .el-icon .el-icon-arrow-left {
         font-size: 50px;
         height: 60px;
         width: 40px;
     }
    /deep/ .el-pager li{
         margin-top: 15px;
         height: 60px;
         width: 60px;
         line-height: 60px;
         font-size: 18px;
     }
    /deep/  .el-pagination.is-background .btn-prev, .el-pager li{
        height: 60px;
        width: 60px;
    }/deep/ .el-pagination.is-background .btn-next, .el-pager li{
         height: 60px;
         width: 60px;
     }/deep/ .el-pagination .btn-prev  .el-icon{
          font-size: 40px;
      }/deep/ .el-pagination .btn-next .el-icon{
           font-size: 40px;
       }
    /*分页修改结束*/

    @media (max-width: 1366px) {
        #emergencyNumberManage .table-wrap {
            height: 800px !important;;
            overflow: auto;
        }
    }

    .searchFormBtn {
        margin-left: 5px;
        display: inline-block;
    }
</style>
